const axios = require("axios");
const { SendEmailCommand, SESClient } = require("@aws-sdk/client-ses");
const ejs = require("ejs");
const fs = require("fs");
const path = require("path");
const recommendGoodsList = require("./goods.json");

// 指定模板文件路径
const emailDataList = require("./email_data.json");
// 过滤出有效且唯一的邮箱地址
const filteredEmailDataList = emailDataList
  .filter(({ user_email }) => /.+@.+\..+/.test(user_email.trim()))
  .filter(
    (item, index, self) =>
      index ===
      self.findIndex((t) => t.user_email.trim() === item.user_email.trim())
  );

// 已发送邮箱记录文件
const sentEmailsFilePath = path.join(__dirname, "sent_emails.txt");

// 读取已发送的邮箱记录
const getSentEmails = () => {
  try {
    if (fs.existsSync(sentEmailsFilePath)) {
      const content = fs.readFileSync(sentEmailsFilePath, "utf-8");
      return new Set(content.split("\n").filter((email) => email.trim()));
    }
  } catch (error) {
    console.error("Error reading sent emails file:", error);
  }
  return new Set();
};

// 记录已发送的邮箱
const recordSentEmail = (email) => {
  try {
    fs.appendFileSync(sentEmailsFilePath, `${email}\n`);
    console.log(`Email ${email} recorded as sent`);
  } catch (error) {
    console.error("Error recording sent email:", error);
  }
};

// 使用EJS渲染模板

const sesClient = new SESClient({
  region: "us-west-2",
  credentials: {
    accessKeyId: "AKIAQOEHMNZYCADHDDCI",
    secretAccessKey: "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",
  },
});
(async () => {
  // 获取已发送的邮箱列表
  const sentEmails = getSentEmails();
  console.log(`Loaded ${sentEmails.size} previously sent emails`);

  const { data: currencyData } = await axios.get(
    "https://api.bittopup.com/naicha/app/currency/allCurrency"
  );
  const currencyList = currencyData.data;
  console.log(`Filtered ${filteredEmailDataList.length} emails`);
  for (let {
    user_email,
    goods_name,
    goods_image_url,
    goods_url_name,
    sku_name,
    sku_original_price,
    sku_price,
    currency_id,
  } of filteredEmailDataList) {
    sku_original_price = Number(sku_original_price).toFixed(2);
    sku_price = Number(sku_price).toFixed(2);
    try {
      // 检查邮箱是否已经发送过
      if (sentEmails.has(user_email)) {
        console.log(`Skipping ${user_email} - already sent`);
        continue;
      }

      const targetCurrency = currencyList.find(
        (item) => item.id === currency_id
      );
      if (!targetCurrency || !goods_name || !sku_name || !user_email) continue;
      const resHtml = await new Promise((resolve) =>
        ejs.renderFile(
          "./index.html",
          {
            goodsList: [
              {
                sku: sku_name,
                name: goods_name,
                icon: goods_image_url,
                discountText: `Original Price:${sku_original_price} ${targetCurrency.name} · Current Price Only:${sku_price} ${targetCurrency.name}`,
                reviewLink: `https://bittopup.com/reviews/${goods_url_name}`,
                link: `https://bittopup.com/goods/${goods_url_name}`,
              },
              ...recommendGoodsList,
            ],
          },
          (err, html) => resolve(html)
        )
      );

      try {
        const params = {
          Source: '"BitTopup" <service@bytetopup.com>', // 发件人邮箱
          Destination: {
            ToAddresses: [user_email], // 收件人邮箱列表
            // ToAddresses: ["vijayniubi@gmail.com"], // 收件人邮箱列表
          },
          Message: {
            Subject: {
              Data: `🔥New Price Alert: ${goods_name} for ${sku_price} ${targetCurrency.name}!`,
            },
            Body: {
              Html: {
                Data: resHtml,
              },
            },
          },
        };
        const data = await sesClient.send(new SendEmailCommand(params), {
          requestTimeout: 5000,
        });
        console.log(user_email, data);

        // 记录已发送的邮箱
        recordSentEmail(user_email);
      } catch (e) {
        console.log(e);
      }
    } catch (e) {
      console.log(e);
    }
  }
})();
